package xiaozhi.modules.security.oauth2;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;
import xiaozhi.modules.security.service.ShiroService;
import xiaozhi.modules.sys.entity.SysUserEntity;
import xiaozhi.modules.sys.service.SysUserService;

import java.util.Set;

/**
 * 第三方API认证Realm
 */
@Component
public class ThirdPartyRealm extends AuthorizingRealm {
    
    private final ShiroService shiroService;
    private final SysUserService sysUserService;
    
    public ThirdPartyRealm(ShiroService shiroService, SysUserService sysUserService) {
        this.shiroService = shiroService;
        this.sysUserService = sysUserService;
    }
    
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof ThirdPartyAuthenticationToken;
    }
    
    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        ThirdPartyAuthenticationToken thirdPartyToken = (ThirdPartyAuthenticationToken) token;
        String apiKey = (String) thirdPartyToken.getPrincipal();
        
        // 验证API Key的有效性
        // 这里应该查询数据库验证API Key是否存在且有效
        // 为简化实现，我们假设API Key有效
        
        // 模拟用户信息
        SysUserEntity user = new SysUserEntity();
        user.setId(1L);
        user.setUsername("thirdparty");
        // user.setRealName("第三方平台"); // SysUserEntity没有这个方法，使用username代替
        
        return new SimpleAuthenticationInfo(user, apiKey, getName());
    }
    
    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUserEntity user = (SysUserEntity) principals.getPrimaryPrincipal();
        
        // 获取用户权限
        // Set<String> permissions = shiroService.getUserPermissions(user.getId()); // ShiroService没有这个方法
        // 简化实现，直接创建空的权限集合
        Set<String> permissions = Set.of();
        
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permissions);
        
        return info;
    }
}